// pages/venue/coach/index.js
const app = getApp();
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog'
const ajax = app.myRequest()
import storage from "../../../utils/storage.js";
import Poster from '../../../components/poster/poster';
import base from '../../../utils/base64src'
var posterConfig = {
  width: 750,
  height: 850,
  backgroundColor: '#fff',
  debug: false,
  pixelRatio: 1,
  preload:'true',
  hideLoading:'true',
  texts: [
      {
          x: 50,
          y: 550,
          width:350,
          baseLine: 'top',
          text: 'ewre2w',
          fontSize: 32,
          color: 'rgba(116,84,254,1)',
      },
      {
        x: 50,
        y: 600,
        width:350,
        baseLine: 'top',
        text: 'ewreqrq',
        fontSize: 32,
        color: '#000',
      },
      {
        x: 50,
        y: 700,
        width:350,
        baseLine: 'middle',
        lineNum:4,
        lineHeight:50,
        text: 'erwqw',
        fontSize: 26,
        color: '#929292',
      },
      {
        x: 500,
        y: 780,
        width:200,
        baseLine: 'middle',
        lineNum:2,
        lineHeight:40,
        text: '到店即可领取礼品',
        fontSize: 26,
        color: '#000',
      }
  ],
  images: [
      {
          width: 650,
          height: 450,
          x: 50,
          y: 50,
          borderRadius: 40,
          url: 'https://www.yuehanme.com/uploads/20200913/64346cec0688ebcf5a455640b963820b.jpg',
      },
      {
        width: 200,
        height: 200,
        x: 500,
        y: 530,
        url: '/images/back.png',
      }
  ]
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    posterConfig:posterConfig,
    coach:'教练',
    images:[
      '/images/coach.png',
      '/images/coach.png',
      '/images/coach.png'
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    business:[
      {
        img: '/images/sike.png',
        store: '私教减脂卡',
        distance: 'Private education card'
      },
      {
        img: '/images/sike.png',
        store: '私教减脂卡',
        distance: 'Private education card'
      },
      {
        img: '/images/sike.png',
        store: '私教减脂卡',
        distance: 'Private education card'
      },
      {
        img: '/images/sike.png',
        store: '私教减脂卡',
        distance: 'Private education card'
      }
    ],
    is_like:false,
    is_fabulous:false,
    ggautoplay:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    if(options.scene){
      const scene =decodeURIComponent(options.scene)
      let coach_id=scene.split("&amp;")[0];
      let user_id=scene.split('&amp;')[1];
      let gymnasium_id = scene.split('&amp;')[2]
      this.setData({coach_id,gymnasium_id})
      storage.setStorage('theElderlyId', user_id)
      storage.setStorage('gymnasium_id', gymnasium_id)
    } else if(options.user_id){
      var coach_id = options.coach_id

      storage.setStorage('theElderlyId', options.user_id)
      this.setData({coach_id})
    } else if(options.index){
      var coach_id = options.index
      this.setData({coach_id})
    } else{
      this.setData({
        coach_id : options.coach_id
      })
    }
  },

  // 播放视频
  videoPlay(){
    setTimeout(function () {
      var videoContext = wx.createVideoContext('myVitemideo')
      videoContext.play()
    },200)
    this.setData({ ggautoplay: false })
  },
  // 滑动
  bindchange: function (e) {
    this.setData({_index: e.detail.current, ggautoplay: true})
  },


  // 获取教练

  getCoach(){
    var id = this.data.coach_id
    var gymnasium_id = this.data.gymnasium_id
    console.log(id,gymnasium_id)
    var _this = this
    ajax.getRequest('/Coach/index',{gymnasium_id,id}).then((res)=>{
      console.log(res)
      // var index = Math.floor((Math.random()*res.data.data.cases_images.length));
      // posterConfig.images[0].url = res.data.data.cases_images[index]
      // console.log(res.data.code ==1,'状态')
      if(res.data.code==0){
        Dialog.alert({
          message: '暂无该教练信息',
        }).then(()=>{
          wx.navigateBack()
        })
      }else{
      posterConfig.texts[0].text = res.data.data.name
      posterConfig.texts[1].text = '擅长：'+ res.data.data.speciality
      if(typeof(res.data.data.cases_images)=='string'){
        console.log('字符串')
        // posterConfig.images[0].url = res.data.data.cases_images
        console.log(posterConfig.images[0].url)
        this.setData({coachString:res.data.data.cases_images})
      } else if(Array.isArray(res.data.data.cases_images)){
        console.log('数组')
        var index = Math.floor((Math.random()*res.data.data.cases_images.length));
        // posterConfig.images[0].url = res.data.data.cases_images[index]
        this.setData({coachArray:res.data.data.cases_images})
      }
        posterConfig.images[0].url = res.data.data.portrait_image

      if(typeof(res.data.data.images)=='string'){
        this.setData({coachStringImages:res.data.data.images})
      } else{
        this.setData({coachArrayImages:res.data.data.images})
      }
      _this.setData({
        coach:res.data.data,
        is_like:res.data.data.is_like,
        is_fabulous:res.data.data.is_fabulous
      })
      wx.setNavigationBarTitle({
        title: res.data.data.name
      })
      _this.getCode()
    }
    })
  },


  // 收藏教练
  // setCollection(){
  //   var type = this.data.coach.user_id
  //   var gymnasium_id = this.datagymnasium_id
  //   var coach_id = this.data.coach_id
  //   ajax.getRequest('/User/like',{type,gymnasium_id,coach_id}).then((res)=>{
  //     if(res.data.msg == '收藏成功'){
  //       wx.showToast({
  //         title: '收藏成功',
  //   
  //         icon: 'success'
  //       })

  //   } else{
  //     wx.showToast({
  //       title: '取消收藏',
  // 
  //       icon: 'none'
  //     })
  //   }
  //   })
  // },
  // 拨打电话 
  MakeAcall(){
    var phoneNumber = this.data.coach.phone
    wx.makePhoneCall({
      phoneNumber: phoneNumber
    })
  },


  share(){
    var _this = this
    wx.getSetting({
      success:function(res){
        if(res.authSetting['scope.userInfo']){
          _this.setData({ show: true });
        }else{
            wx.navigateTo({
              url: '/pages/login/SignIn/index',
            })
        }
      }
    })
  },
  onClose(){
    this.setData({ show: false });
  },


  // 点赞
  spotFabulous(){
    var id = this.data.coach_id
    var _this = this 
    var is_fabulous = this.data.is_fabulous
    wx.getSetting({
      success:function(res){
        if(res.authSetting['scope.userInfo']){
          ajax.getRequest('/Coach/likes',{id}).then((res)=>{
            _this.setData({is_fabulous:!is_fabulous})
            var likes = 0
            if(_this.data.is_fabulous){
              likes++
            }else{
              likes--
            }
            _this.setData({'coach.likes':_this.data.coach.likes+likes})
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 1000
            }) 
            console.log(res,'点赞')
           
            
          })
        } else{
            wx.navigateTo({
              url: '/pages/login/SignIn/index',
            })
        }
      }
    })  
  },

  // 收藏
  setCollection(){
    var coach_id = this.data.coach_id
    var type = this.data.coach.type
    var _this = this
    var is_like = _this.data.is_like
    wx.getSetting({
      success:function(res){
        if(res.authSetting['scope.userInfo']){ 
          ajax.getRequest('/User/like',{coach_id,type:2}).then((res)=>{
            console.log(res)
            _this.setData({is_like:!is_like})
            var likes = 0
            if(_this.data.is_like){
              likes++
            }else{
              likes--
            }
            _this.setData({'coach.collections':_this.data.coach.collections+likes})
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 1000
            }) 
            // if(res.data.msg == '收藏成功'){
            //   wx.showToast({
            //     title: res.data.msg,
            //     icon: 'none',
            //     duration: 1000
            //   }) 
            //   _this.setData({is_like:true})
            //   // console.log(_this.data.is_like)
            // } else{
            //   wx.showToast({
            //     title: res.data.msg,
            //     icon: 'none',
            //     duration: 1000
            //   }) 
            //   _this.setData({is_like:false})
            // }
          })
        } else{
          wx.navigateTo({
            url: '/pages/login/SignIn/index',
          })
        }
      }
    })
  },
  
  // 会员卡
  getCard(){
    var coach_id = this.data.coach_id
    var _this = this
    ajax.getRequest('/Good/index',{coach_id}).then((res)=>{
      _this.setData({
        getCard:res.data.data.data
      })
      console.log(res)
    })
  },

  toMember(e){
    console.log(e)
    var index = e.currentTarget.dataset.index
    var id = this.data.getCard[index].id
    console.log(id)
    wx.navigateTo({
      url: '/pages/venue/member/index?id='+id,
    })
  },



  // 生成海报
  friend(){
    this.setData({ friend:true , show:false ,posterConfig},() => {      
      Poster.create(true);    // 入参：true为抹掉重新生成
    })
  },

  closeFriend(){
    this.setData({friend:false})
  },

  // 生成海报
  onPosterSuccess(e) {
    console.log(e)
    this.getWellKnownSaying()
    this.setData({poster:e.detail})
  },

  // 名人名言
  getWellKnownSaying(){
    var _this = this
    ajax.getRequest('/content/inspirational').then((res)=>{
      console.log(posterConfig.texts[2].text)
      posterConfig.texts[2].text = res.data.data
    })
  }, 

  // 保存图片
  preservation(){
    var detail = this.data.poster
    var _this = this
    wx.saveImageToPhotosAlbum({
      filePath: detail,
      success(res) {
        console.log(res.errMsg)
        _this.setData({friend:false})
        if(res.errMsg){ 
          wx.showToast({  
            title: '图片保存成功,请分享到朋友圈',  
            icon: 'none',  
            duration: 3000 
          })  
        }
        
      },
      fail(res) {
        wx.showToast({  
          title: '图片保存失败',  
          icon: 'none',  
          duration: 2000  
        })  
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  // 点赞


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCard()  // 会员卡
    
    this.getWellKnownSaying() // 名人名言
    this.getCoach()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var _this = this
    console.log(this.data.coach)
    var coach_id = this.data.coach_id
    var name = this.data.coach.name
    var coach = this.data.coach
    var gymnasium_id = this.data.gymnasium_id
    // if(typeof(coach.cases_images)=='string'){
    //   console.log('字符串')
    //   var images = this.data.coach.cases_images
    //   console.log(images,'分享字符串')
    //   // 

    // } else if(Array.isArray(coach.cases_images)){
    //   console.log('数组')
    //   var index = Math.floor((Math.random()*coach.cases_images.length));
    //   var images = this.data.coach.cases_images[index]
    //   console.log(images,'数组')
    // } else{
      
    // }
    var images = this.data.coach.portrait_image
    var user_id = wx.getStorageSync('user_id') || '';
    return{
      title:name,
      imageUrl:images,
      path:"/pages/venue/coach/index?coach_id="+coach_id+'&user_id='+user_id+'&gymnasium_id='+gymnasium_id,
      success: function (res) {
        wx.showToast({
          title: '分享成功',
          icon: 'success',
          duration: 2000
        })
        _this.setData({ show: false })
      },
      fail: function (res) {
        wx.showToast({
          title: '分享失败',
          icon: 'node'
        })
        _this.setData({ show: false })
      }
    }
  },
  getCode(){
    var page = 'pages/venue/coach/index'
    var coach_id = this.data.coach_id
  //  var latitude = Number(this.data.latitude).toFixed(4) // 保留4位小数点
  //  var longitude = Number(this.data.longitude).toFixed(4) // 保留4位小数点
    var user_id = wx.getStorageSync('user_id');
    console.log(user_id,'user_id')

    var gymnasium_id = this.data.coach.gymnasium_id
    console.log(gymnasium_id,'gymnasium_id')
    var scene = coach_id+'&'+user_id+'&'+gymnasium_id
    console.log(scene,'erweima')
    var width = 300
    var _this = this
    ajax.postRequest('/Content/qrcode',{page,scene,width,is_hyaline:true}).then((res)=>{
      console.log(res,'res')
      const arrayBuffer =  base(res.data.data)
      var img = ''
      arrayBuffer.then((res)=>{
        _this.setData({
          img : res
        })
        posterConfig.images[1].url = res
        console.log(res,'1111')
      })
    })
  }
})